import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../modules/user/entities/user.entity';
import { JWT_SECRET } from '../config/jwt.config';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: JWT_SECRET,
    });
  }

  async validate(payload: any) {
    try {
      console.log('JWT 策略 - 验证 payload:', payload);
      
      if (!payload || !payload.sub) {
        throw new UnauthorizedException('无效的 token payload');
      }
      
      const user = await this.userRepository.findOne({
        where: { id: payload.sub }
      });

      console.log('JWT 策略 - 查询到的用户:', user);

      if (!user) {
        throw new UnauthorizedException('用户不存在或已被删除');
      }

      // 确保返回的用户信息包含 username
      return { 
        id: payload.sub, 
        username: user.username || user.phone || `user_${user.id}` 
      };
    } catch (error) {
      console.error('JWT策略 - 验证过程出错:', error);
      throw error;
    }
  }
}
